package com.yanfan.zutai.config;


import com.alibaba.fastjson2.JSONObject;
import com.yanfan.common.core.mq.DeviceReport;
import com.yanfan.common.core.redis.RedisCache;
import com.yanfan.common.core.thingsModel.ThingsModelSimpleItem;
import com.yanfan.framework.manager.AsyncManager;
import com.yanfan.mq.service.IMqttMessageService;
import com.yanfan.mqtt.manager.MqttRemoteManager;
import com.yanfan.mqtt.model.PushMessageBo;
import com.yanfan.zutai.domain.BDeviceHistoryData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class ZutaiMqttServiceImpl implements IMqttMessageService {
    public static final String ZT_DATA_KEY = "ZT_DATA:";

    @Resource
    private MqttRemoteManager remoteManager;
    @Resource
    private RedisCache redisCache;
    @Autowired
    private MqttDataServiceImpl mqttDataService;
    @Value("${server.zutai.enabled:false}")
    private Boolean zutaiEnabled;

    @Override
    public void message(DeviceReport message, String topicName) {
        if (zutaiEnabled) {
            pushMessage(message);
        }
    }

    public void pushMessage(DeviceReport message) {
        // 通过内部mqtt客户端下发消息
        PushMessageBo zutaiBo = new PushMessageBo();
        // 通过内部mqtt客户端下发消息
        zutaiBo.setQos(1);
        if (message.getType() == null || !message.getType().equals("1")) {
            Map<String, String> collect = message.getThingsModelSimpleItem()
                    .stream()
                    .collect(Collectors.toMap(ThingsModelSimpleItem::getId, ThingsModelSimpleItem::getValue));
            // 判断是不是子设备 FIXME
            if (Objects.nonNull(message.getSlaveId())) {
                // message.getValuesInput().getDeviceNumber()
                zutaiBo.setTopic("/IOT/WULIANYUN/REALDATA/" + message.getSerialNumber() + "_" + message.getSlaveId());
            } else {
                zutaiBo.setTopic("/IOT/WULIANYUN/REALDATA/" + message.getSerialNumber());
            }
            zutaiBo.setMessage(JSONObject.toJSONString(collect));
            remoteManager.pushCommon(zutaiBo);
            // 加入缓存中去，为初始化组态提供数据
            for (ThingsModelSimpleItem thingsModelSimpleItem : message.getThingsModelSimpleItem()) {
                redisCache.setHashValue(ZT_DATA_KEY + message.getSerialNumber(), thingsModelSimpleItem.getId(), thingsModelSimpleItem.getValue());
            }

            AsyncManager.me().execute(new TimerTask() {
                @Override
                public void run() {
                    // 插入变量历史数据,改用taos时序数据库
                    BDeviceHistoryData historyData = new BDeviceHistoryData();
                    historyData.setDeviceImei(message.getSerialNumber());
                    historyData.setDeviceName(message.getDeviceName());
                    historyData.setParamUnit(null);
                    for (ThingsModelSimpleItem thingsModelSimpleItem : message.getThingsModelSimpleItem()) {
                        historyData.setReportTime(thingsModelSimpleItem.getTs());
                        historyData.setParamField(thingsModelSimpleItem.getId());
                        historyData.setParamName(thingsModelSimpleItem.getRemark());
                        historyData.setParamValue(thingsModelSimpleItem.getValue());
                        try {
                            mqttDataService.insertTaosHistory(historyData);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
            });
        } else {
            zutaiBo.setTopic("/IOT/WULIANYUN/REALDATA/" + message.getSerialNumber());
            Map<String, String> map = new HashMap<>();
            map.put("deviceMac", message.getSerialNumber());
            map.put("warnMessage", message.getAlertName());
            map.put("deviceName", message.getDeviceName());
            Date date = new Date();
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy年MM月dd日HH时mm分ss秒");
            String formattedDate = dateFormat.format(date);
            map.put("warnTime", formattedDate);
            zutaiBo.setMessage(JSONObject.toJSONString(map));
            remoteManager.pushCommon(zutaiBo);
        }

    }


}
